<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker
            v-if="vdata.showDateTimeRage"
            ref="dateRangePicker"
            v-model:value="vdata.searchData['queryDateRange']"
            customDateRangeType="date"
          />
        </a-form-item>
        <jeepay-text-up v-model:value="vdata.searchData['agentNo']" :placeholder="'代理商号'" />
        <jeepay-text-up v-model:value="vdata.searchData['agentName']" :placeholder="'代理商名称'" />
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :init-data="false"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="vdata.searchData"
        row-key="agentNo"
        :statisticsIsShow="true"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="btnLoading=false"
        @handleTableChange="handleChange"
      >
        <template #headerCell="{ column }">
          <span v-if="column.tooltipTitle">
            {{ column.title }}
            <a-tooltip :title="column.tooltipTitle"><info-circle-outlined /></a-tooltip>
          </span>
        </template>
        <template #topBtnSlot>
          <a-button type="primary" @click="tableExportFunc">
            <plus-outlined />导出表格
          </a-button>
        </template>
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in count" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
              </div>
            </div>
          </div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'agentName'">
            <a>
              <b>{{ record.agentName }}</b>
            </a>
          </template>
          <template v-if="column.key === 'allAmount'">
            <b style="color: #15B86C;">￥{{ record.allAmount / 100 }}</b>
          </template>
          <template v-if="column.key === 'payAmount'">
            <b style="color: #15B86C;">￥{{ record.payAmount / 100 }}</b>
          </template>
          <template v-if="column.key === 'refundAmount'">
            <b style="color: #FF6848;">￥{{ record.refundAmount / 100 }}</b>
          </template>
          <template v-if="column.key === 'refundCount'">
            <b style="color: #FF6848;">{{ record.refundCount }}</b>
          </template>
          <template v-if="column.key === 'payCount'">
            <b style="color: #15B86C;">{{ record.payCount }}/{{ record.allCount }}</b>
          </template>
          <template v-if="column.key === 'round'">
            <b style="color: #FF8800;">{{ record.round }}%</b>
          </template>
          <template v-if="column.key === 'agentProfit'">
            <b style="color: #FF6848;">￥{{ record.agentProfit ? record.agentProfit / 100 : 0 }}</b>
          </template>
          <template v-if="column.key === 'operation'">
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_STATISTIC_MCH')" type="link" @click="toPage(record.agentNo, vdata.parameterDate)">商户统计</a-button>
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
  </page-header-wrapper>
</template>
<script setup lang="ts">

import { API_URL_STATISTIC, req, $exportExcel, exportExcelUrl } from '@/api/manage'
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import fileDownload from 'js-file-download'
import dateUtil from '@/utils/dateUtil.js'
const { $infoBox, $access, $hasAgentEnt } = getCurrentInstance()!.appContext.config.globalProperties

const infoDetail = ref()
const infoTable = ref()
let tableColumns = reactive([
  { key: 'agentName', title: '代理商名称', dataIndex: 'agentName', },
  { key: 'agentNo', title: '代理商号', dataIndex: 'agentNo', agentEntCol: true, },
  { key: 'allAmount', title: '成交金额', tooltipTitle: '支付成功的订单金额，包含部分退款及全额退款的订单', dataIndex: 'allAmount', },
  { key: 'agentProfit', title: '代理商佣金', tooltipTitle: '成交订单产生的代理商佣金', dataIndex: 'calProfitAmount', },
  { key: 'refundAmount', title: '退款金额', dataIndex: 'refundAmount', },
  { key: 'refundCount', title: '退款笔数', tooltipTitle: '实际退款订单笔数，若一笔已成交订单退款多次，则计多次', dataIndex: 'refundCount',},
  { key: 'payCount', title: '成交/总笔数', dataIndex: 'payCount', },
  { key: 'round', title: '成功率', tooltipTitle: '成交笔数与总订单笔数除得的百分比', dataIndex: 'round',},
  { key: 'operation', title: '操作', fixed: 'right', align: 'center'}
])

  let btnLoading = ref(false)
  let count:any = ref([]) // 数据统计数组

  const dateRangePicker = ref()
  const vdata : any = reactive({
    searchData: { method : 'agent', queryDateRange: 'today', sortField: 'payAmount', sortOrder: 'descend' },
    showDateTimeRage: false,
    parameterDate: 'today'
  })

  vdata.searchData['isvNo'] = useRoute().query.isvNo

  onMounted(() => {
    if(useRoute().query.queryDate) {
      vdata.searchData['queryDateRange'] = dateUtil.parseQueryStringByRange(useRoute().query.queryDate)
    }
    searchFunc()
    vdata.showDateTimeRage = true
  })

  function handleChange(sorter) {
    vdata.searchData['sortField'] = sorter.columnKey
    vdata.searchData['sortOrder'] = sorter.order
  }

  function resetFunc() {
    dateRangePicker.value.returnSelectModel()
    vdata.searchData = { method : 'agent', queryDateRange: 'today', sortField: 'payAmount', sortOrder: 'descend' }
  }

function searchFunc() { // 点击【查询】按钮点击事件
    vdata.parameterDate = vdata.searchData.queryDateRange
    infoTable.value.refTable(true)
  }

  // 请求table接口数据
  function reqTableDataFunc(params: any) {
    params.method = 'agent'
    
    if (!params.sortField) {
      params.sortField = 'payAmount'
      params.sortOrder = 'descend'
    }

    reqTableCountFunc(params)
    return req.list(API_URL_STATISTIC, params)
  }

    // 请求table接口数据
  function reqTableCountFunc(params: any) {
    req.list(API_URL_STATISTIC + '/total', params).then(res => {
    count.value = [
        {title: '总成交金额', symbol: 'add', textColor: '#1A66FF', content: ((res.allAmount) / 100).toFixed(2)},
        {type: 'line'},
        {title: '总成交笔数', content: (res.payCount)},
        {type: 'line'},
        {title: '总退款金额', symbol: 'sub', content: ((res.refundAmount) / 100).toFixed(2)},
        {type: 'line'},
        {title: '总退款笔数', content: (res.refundCount)},
        {type: 'line'},
        {title: '支付成功率', content: (res.round) + '%'},
      ]
    })
  }

  function tableExportFunc(){
    return $exportExcel(exportExcelUrl.statistic, Object.assign({}, vdata.searchData, {})).then(res => {
        fileDownload(res.data, '代理商统计.xlsx')
    }).catch ((error) =>{console.log(error)} )
  }

function toPage(recordId, date) {
    if (date.indexOf('_7') > -1) {
      date = 7
    } else if (date.indexOf('_30') > -1) {
      date = 30
    } else if (date.indexOf('customDateTime') > -1) {
      date = dateUtil.getCustomDateTime(date)
    }
    router.push({
      path: '/statistic/mch',
      query: { agentNo: recordId, queryDateRange: date }
    })
  }

</script>
